package com.hui.dbmigrator.controller;

import com.hui.dbmigrator.config.DatabaseConfig;
import com.hui.dbmigrator.dto.request.CreateTableRequest;
import com.hui.dbmigrator.dto.response.ApiResponse;
import com.hui.dbmigrator.handler.DatabaseHandler;
import com.hui.dbmigrator.service.DatabaseService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/databases")
@RequiredArgsConstructor
public class DatabaseController {

    private final DatabaseService databaseService;

    @GetMapping("/supported")
    public ApiResponse<List<String>> getSupportedDatabases() {
        return ApiResponse.success(databaseService.getSupportedDatabases());
    }

    @PostMapping("/tables/create")
    public ApiResponse<String> createTable(
            @RequestBody @Valid CreateTableRequest request) {

        try {
            DatabaseHandler handler = databaseService.getHandler(request.getDatabase().getType().getDisplayName());
            String ddl = handler.generateCreateTable(request.getTableDefinition());
            handler.execute(request.getDatabase(), ddl);
            return ApiResponse.success(ddl);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    @GetMapping("/tables")
    public ApiResponse<List<String>> getTableNames(
            @RequestParam String dbType,
            @RequestBody @Valid DatabaseConfig config) {

        try {
            DatabaseHandler handler = databaseService.getHandler(dbType);
            return ApiResponse.success(handler.getTableNames(config));
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}
